//
//  MyViewController.m
//  Supervisor
//
//  Created by 小宇 on 2017/5/10.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "MyViewController.h"
#import "MyQRViewController.h"
#import "MyTableViewCell.h"
#import "MyDownloadViewController.h"
#import "BeforeScanSingleton.h"
#import "LoginViewController.h"
#import "ACAlertController.h"
#import "UIImageView+WebCache.h"
#import "ChangePasswordViewController.h"


@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
@property (nonatomic,strong)UITableView *MytableView;
@property (nonatomic,strong)NSArray *identityArr;
@property (nonatomic,strong)NSArray *cellNameArr;
@property (nonatomic,strong)UIImage * image;
@property (nonatomic,copy)NSString * jsoninfo;
@end

@implementation MyViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.edgesForExtendedLayout = UIAccessibilityTraitNone;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addMytableView];
}

- (NSArray *)identityArr{
    if (!_identityArr) {
        _identityArr = @[@"headCell",@"swichCell",@"commonCell"];
    }
    return _identityArr;
}

- (NSArray *)cellNameArr{
    if (!_cellNameArr) {
        _cellNameArr = @[@"我的下载",@"修改密码",@"退出登录"];
    }
    return _cellNameArr;
}

- (void)addMytableView{
    [self.view addSubview:self.MytableView];
}

- (UITableView *)MytableView{
    if (!_MytableView) {
        _MytableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, Main_Screen_Width,self.view.frame.size.height - 49)];
        _MytableView.delegate=self;
        _MytableView.dataSource=self;
        [_MytableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        _MytableView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
        _MytableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _MytableView;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 0;
    }else{
        return self.cellNameArr.count + 3;
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.identityArr[indexPath.section]];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"MyTableViewCell" owner:self options:nil][indexPath.section];
            cell.selectionStyle = UIAccessibilityTraitNone;
        }
    switch (indexPath.section) {
        case 0:{
//            cell.changeUserFace = ^(NSString *userface) {
//                ACAlertController *alert = [[ACAlertController alloc] initWithActionSheetTitles:@[@"相册", @"相机"] cancelTitle:@"取消"];
//                LZYWeakSelf(self)
//                [alert clickActionButton:^(NSInteger index) {
//                    if (index == 0) {
//                        [weakself openAlbum];
//                    }else {
//                        [weakself openCamera];
//                    }
//                }];
//                [alert show];
//            };
            [cell.UserImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DigitalCampus_FileUrl,[[User shareInstance] getUserFace]]] placeholderImage:[UIImage imageNamed:@"userFace"]];
            cell.userNameLabel.text = [[User shareInstance]getUserOrignName];
            break;
        }
        case 1:
            if (indexPath.row == 0) cell.leftTitleNameLabel.text = @"消息声音提醒"; else cell.leftTitleNameLabel.text = @"消息震动提醒";
            break;
        default:
            if (indexPath.row < 2) {
                cell.leftTitleNameLabel.text = self.cellNameArr[indexPath.row];
            }else if (indexPath.row >= 2 && indexPath.row <= 4) {
                cell.hidden = YES;
            }else{
                cell.LeftTitleLabel.hidden = YES;
                cell.rightImgView.hidden = YES;
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(28, 0, Main_Screen_Width - 56, 50) Text:@"退出登录" TextColor:[UIColor whiteColor] TextAlignment:NSTextAlignmentCenter Font:[UIFont systemFontOfSize:17] Target:nil Action:nil];
                label.backgroundColor = MainColor;
                label.layer.cornerRadius = 4;
                label.layer.masksToBounds = YES;
                [cell.contentView addSubview:label];
            }
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)return 205;else return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        if (indexPath.row == 0){
            [self.navigationController pushViewController:[MyDownloadViewController new] animated:YES];
        }else if (indexPath.row == 1){
            [self.navigationController pushViewController:[ChangePasswordViewController new] animated:YES];
        }else if (indexPath.row == 5){
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确认退出" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertview show];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[User shareInstance] loginOut];
        LoginViewController *login = [[LoginViewController alloc]init];
        self.view.window.rootViewController = login;
    }
}

- (void)openAlbum{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    UIImagePickerController *imagePhoto = [[UIImagePickerController alloc] init];
    imagePhoto.sourceType = sourceType;
    imagePhoto.delegate = self;
    imagePhoto.allowsEditing = YES;
    [self presentViewController:imagePhoto animated:YES completion:nil];

}

- (void)openCamera{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *imageCameral = [[UIImagePickerController alloc] init];
    imageCameral.sourceType = sourceType;
    imageCameral.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    imageCameral.delegate = self;
    imageCameral.allowsEditing = YES;
    [self presentViewController:imageCameral animated:YES completion:nil];
}

#pragma mark - UIAlertControllerDelegate
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.image = [info objectForKey:UIImagePickerControllerEditedImage];
    //设置image的尺寸
    CGSize imagesize = self.image.size;
    imagesize.height =65;
    imagesize.width =65;
    
    self.image = [self imageWithImage:self.image scaledToSize:imagesize];
    
    [self uploadHeadImage];
}

- (void)uploadHeadImage {
    [LZYNetworkHelper uploadWithURL:uploadFace parameters:@{@"accessToken":[[User shareInstance]getUserAccessToken],@"userId":[[User shareInstance] getUserId]} images:@[self.image] name:@"myfiles" fileName:@"FileData" mimeType:@"png" progress:^(NSProgress *progress) {
        [SVProgressHUD showProgress:progress.fractionCompleted status:@"正在上传"];
    } success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 1) {
            [SVProgressHUD dismiss];
            NSString *userFace = responseObject[@"obj"];
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
            MyTableViewCell *cell = [self.MytableView cellForRowAtIndexPath:indexpath];
            [cell.UserImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DigitalCampus_FileUrl,userFace]] placeholderImage:[UIImage imageNamed:@"userFace"]];
            [[User shareInstance] changeUserFace:userFace];
        }
    } failure:^(NSError *error) {
        [LZYShowMsg showText:@"图片更新失败"];
    } showHub:YES];
}



//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize

{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

@end
